package com.zoe.onelink.dubbo.filter;

import com.zoe.onelink.util.OnelinkContextHolder;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.Filter;
import org.apache.dubbo.rpc.Invocation;
import org.apache.dubbo.rpc.Invoker;
import org.apache.dubbo.rpc.Result;
import org.apache.dubbo.rpc.RpcContext;
import org.apache.dubbo.rpc.RpcException;

import java.util.Map;

import static org.apache.dubbo.common.constants.CommonConstants.CONSUMER;
import static org.apache.dubbo.common.constants.CommonConstants.PROVIDER;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2022</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2022-05-26
 */
@Activate(group = {CONSUMER, PROVIDER}, order = -2000)
public class DubboContextFilter implements Filter {

    private static final String ONELINK_CONTEXT_HOLDER_KEY = "onelink_ctx_holder";

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        RpcContext context = RpcContext.getContext();
        if (context.isConsumerSide()) {
            context.setObjectAttachment(ONELINK_CONTEXT_HOLDER_KEY, OnelinkContextHolder.getCopiedMap());
        } else {
            Object contextHolderAttachment = context.getObjectAttachment(ONELINK_CONTEXT_HOLDER_KEY);
            if (contextHolderAttachment instanceof Map) {
                OnelinkContextHolder.putValue((Map<String, Object>) contextHolderAttachment);
            }
        }
        return invoker.invoke(invocation);
    }

}
